#include "Sector.h"
#include "Player.h"
#include "Guard.h"

Sector::Sector()
{


}

bool Sector::Init(std::string filename, Artman *artman,AnimationSolver*animator, Actor *player)
{
	p_animsolver=animator;
	m_actors.push_back(player);
	if (m_level.LoadFromFile(filename,artman)==0)
	{
		return false;
	}
	m_level.SetDrawingBounds(sf::Rect <float>(0,0,1280,768));
	Player *p=(Player *)player;
	p->Link(m_level.getSolver());
	
	if (!LoadEnemies(artman))
	{
		return false;
	}


	return true;
}

bool Sector::LoadEnemies(Artman *artman)
{
	std::vector <Object> *levelobjects=m_level.getObjectlist();
	if (levelobjects->size()>0)
	{
		for (int i=0;i<levelobjects->size();i++)
		{
			Object object=levelobjects->operator[](i);
			if (object.type=="enemy")
			{
				std::string type=object.GetPropertyString("type");
				sf::Vector2f position=sf::Vector2f(object.rect.left,object.rect.top);
				if (type=="guard")
				{
					Character *actor=new Guard(position,object.GetPropertyInt("flip"),artman,p_animsolver);
					m_actors.push_back(actor);
					actor->Link(m_level.getSolver());
					m_level.getSolver()->Link(&m_actors);
				}
			}
		}
	}
	return true;
}

Sector *Sector::Create(std::string filename,Artman *artman,AnimationSolver*animator, Actor *player)
{
	Sector *sector=new Sector();
	if (sector->Init(filename,artman,animator,player))
	{
		return sector;
	}
	delete sector;
	return NULL;
}

Sector::Sector (std::string filename, Actor *player)
{



}

Sector::~Sector()
{
	if (m_actors.size()>0)
	{
		for (int i=0;i<m_actors.size();i++)
		{
			delete m_actors[i];
		}
	}


}

void Sector::Update(float dt)
{
	if (m_actors.size()>0)
	{
		for (int i=0;i<m_actors.size();i++)
		{
			m_actors[i]->Update(dt);

		}
	}
	m_level.getSolver()->Update(dt);
}

sf::Vector2 <int> Sector::getBounds()
{
	return m_level.getSize();

}

void Sector::Draw(sf::RenderWindow &window)
{
	if (m_actors.size()>0)
	{
		for (int i=0;i<m_actors.size();i++)
		{
			window.draw(*m_actors[i]);
			m_actors[i]->ExtraDraw(window);
		}
	}

}